package com.dxd.onlineshop.service.impl;

import com.dxd.onlineshop.mapper.UserMapper;
import com.dxd.onlineshop.pojo.Cart;
import com.dxd.onlineshop.pojo.User;
import com.dxd.onlineshop.service.UserService;
import com.dxd.onlineshop.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private com.dxd.onlineshop.mapper.goodsMapper goodsMapper;

    //更新用户信息
    @Override
    public User updateUserInfo(User user, String token) {

        try {
            Map<String, Object> map = JwtUtil.parseToken(token);
            int id = (int) map.get("userId");
            user.setId(id);
            // 调用 Mapper 方法更新用户信息
            int rowsAffected = userMapper.updateUser(user);

            if (rowsAffected > 0) {
                return userMapper.getUserById(id);
            } else {
                throw new RuntimeException("更新失败");
            }
        }catch (Exception e) {
            throw new RuntimeException("更新失败: " + e.getMessage());
        }

    }

    //获取用户信息
    @Override
    public User getUserInfo(int id) {
        // 调用 Mapper 方法获取用户信息
        return userMapper.getUserById(id);
    }

    //获取用户余额
    @Override
    public int getUserBalanceById(int userId){
        //调用Mapper方法获取用户余额
        return userMapper.getUserBalanceById(userId);
    }

    //扣除余额
    @Override
    @Transactional
    public boolean deductBalance(Integer userId, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("扣除金额必须大于0");
        }
        int result = userMapper.deductBalance(userId, amount);
        return result > 0;
    }

    //充值余额
    @Override
    @Transactional
    public boolean addBalance(Integer userId, int amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("充值金额必须大于0");
        }
        int result = userMapper.addBalance(userId, amount);
        return result > 0;
    }

    //获取用户购物车信息
    @Override
    public List<Cart> getUserCartInfo(Integer userId) {
        List<Cart> cartList = userMapper.getUserCartInfo(userId);
        System.out.println("从数据库获取到数据:" + cartList);
        return cartList;
    }


    //更新商品数量
    @Override
    public boolean updateCartItemQuantity(Integer userId, Integer cartId, Integer quantity) {
        log.info("更新购物车商品数量: userId={}, cartId={}, quantity={}", userId, cartId, quantity);
        int rowsAffected = userMapper.updateCartItemQuantity(cartId, userId, quantity);
        return rowsAffected > 0;
    }

    //移除商品
    @Override
    public boolean removeCartItem(Integer userId, Integer cartId) {
        log.info("从购物车中删除商品: userId={}, cartId={}", userId, cartId);
        int rowsAffected = userMapper.removeCartItem(cartId, userId);
        return rowsAffected > 0;
    }

    //添加商品到购物车(如果存在则修改数量)
    @Override
    public Cart addCartItem(Integer userId, Integer productId, Integer quantity) {
        log.info("添加商品到购物车: userId={}, productId={}, quantity={}", userId, productId, quantity);
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setProductId(productId);
        cart.setQuantity(quantity);
        int rowsAffected = 0;
        //查询是否已经有相同的产品在购物车内
        Cart scanCart  = userMapper.getCartId(productId,userId);
        if (scanCart != null) { //如果产品已经在购物车内则增加数量
            int cartId = scanCart.getCartId();
            int setQuantity = scanCart.getQuantity()+quantity;
            rowsAffected = userMapper.updateCartItemQuantity(cartId,userId,setQuantity);
        } else {
            rowsAffected = userMapper.addCartItem(cart);  //如果购物车内没有改产品则新增一条记录
        }

        if (rowsAffected > 0) {
            int result = goodsMapper.reduceStock(productId,quantity);
            if (result == 0)
            {
                System.out.println("库存不足");
            }
            // 获取新添加的购物车项信息
            List<Cart> updatedCart = userMapper.getUserCartInfo(userId);
            return updatedCart.stream()
                    .filter(item -> item.getProductId().equals(productId))
                    .findFirst()
                    .orElse(null);
        }
        return null;
    }


    //清除购物车
    @Override
    public boolean removeCart(Integer userId) {
        log.info("清空用户购物车: userId={}", userId);
        int rowsAffected = userMapper.removeCart(userId);
        return rowsAffected > 0;
    }

}